from PyQt6.QtCore import Qt
from PyQt6.QtGui import QIcon, QStandardItemModel, QStandardItem, QPixmap, QTextDocument, QTextCursor, \
    QTextCharFormat, QTextBlockFormat, QTextTableFormat, QTextFrameFormat
from PyQt6.QtPrintSupport import QPrintPreviewDialog
from PyQt6.QtWidgets import QMainWindow, QMessageBox

import appvar
import netshop
from ui.PreShop_ui import Ui_MainWindow


class PreShop(QMainWindow, Ui_MainWindow):
    """
    商品选购
    """

    def __init__(self):
        super(PreShop, self).__init__()
        self.setupUi(self)
        self.setWindowIcon(QIcon('image/netshop.jpg'))
        self.setWindowFlag(Qt.WindowType.MSWindowsFixedSizeDialogHint)

        self.lePNm.returnPressed.connect(self.query)
        self.pbQue.clicked.connect(self.query)
        self.tbvCom.clicked.connect(self.showImg)
        self.pbPrint.clicked.connect(self.printTables)
        self.pbPre.setIcon(QIcon('image/cart.jpg'))
        self.pbPre.clicked.connect(self.preShop)
        self.lbUsr.setText('用户：' + appvar.getID())

        self.initTableHeader()

    def initTableHeader(self):
        self.im = QStandardItemModel(self)
        # 设置标题
        for (idx, name) in enumerate(['商品号', '商品名称', '类别', '价格', '库存量']):
            self.im.setHorizontalHeaderItem(idx, QStandardItem(name))
        self.tbvCom.setModel(self.im)
        # 设置列宽
        for (idx, width) in enumerate([70, 300, 60, 70, 40]):
            self.tbvCom.setColumnWidth(idx, width)

    def query(self):
        # 查询
        pnm = self.lePNm.text()
        commodities = []
        for commodity in netshop.query_contains('商品表', 2, pnm):
            commodity = commodity['_val']
            list_val = [commodity[0], commodity[2], commodity[1], commodity[3], commodity[4]]
            commodities.append(list_val)
        self.im.clear()
        self.initTableHeader()
        for r, dict_com in enumerate(commodities):
            # 商品号
            self.im.setItem(r, 0, QStandardItem(str(dict_com[0])))
            # 商品名称
            self.im.setItem(r, 1, QStandardItem(dict_com[1]))
            # 类别
            gtype = netshop.query_first('商品分类表', 0, dict_com[2])
            self.im.setItem(r, 2, QStandardItem(gtype['类别名称']))
            # 价格
            self.im.setItem(r, 3, QStandardItem("%.2f" % dict_com[3]))
            # 库存量
            self.im.setItem(r, 4, QStandardItem(str(dict_com[4])))

    def showImg(self):
        good_id = self.tbvCom.selectedIndexes()[0].data()
        path = 'image/%s.jpg' % good_id
        self.lbImg.setPixmap(QPixmap(path))

    def printTables(self):
        dlg = QPrintPreviewDialog()
        dlg.paintRequested.connect(self.handlePrint)
        dlg.exec()

    def preShop(self):
        """
        选购
        """
        # 查询未结算订单
        set_oid = set(map(lambda item: item['订单号'],
                          netshop.query_not('订单项表', 3, '结算')))
        # 读取订单表
        dict_id = netshop.query_dict('订单表', 0, 1)
        # 比对订单
        found_oid = -1
        for u_oid in set_oid:
            for oid, uid in dict_id.items():
                if u_oid == oid and appvar.getID() == uid:
                    found_oid = oid
                    break
            if found_oid >= 0:
                break
        row = self.tbvCom.currentIndex().row()
        if found_oid < 0:
            # 创建订单
            list_oid = netshop.column('订单表', 0)
            found_oid = max(list_oid) + 1
            row_order = str(netshop.max_row('订单表') + 1)
            sheet_order = {
                'A%s' % row_order: found_oid,
                'B%s' % row_order: appvar.getID(),
                'alignments': ['A%s' % row_order]
            }
            netshop.update_cells('订单表', sheet_order)
        # 选购
        index = self.tbvCom.model().index(row, 0)
        pid = eval(self.tbvCom.model().data(index))
        if netshop.query_first('订单项表', 0, found_oid, (1, pid)) is None:
            row_stat = str(netshop.max_row('订单项表') + 1)
            sheet_stat = {
                'A%s' % row_stat: found_oid,
                'B%s' % row_stat: pid,
                'C%s' % row_stat: '1',
                'D%s' % row_stat: '选购',
                'alignments': ['A%s' % row_stat, 'B%s' % row_stat, 'C%s' % row_stat]
            }
            netshop.update_cells('订单项表', sheet_stat)
            QMessageBox.information(self, '提示', '已选购')
        else:
            QMessageBox.critical(self, '提示', '已选购')

    def handlePrint(self, printer):
        doc = QTextDocument()
        cur = QTextCursor(doc)
        # 标题
        fmt_textchar = QTextCharFormat()
        fmt_textchar.setFontFamily('微软雅黑')
        fmt_textchar.setFontPointSize(10)
        fmt_textblock = QTextBlockFormat()
        fmt_textblock.setAlignment(Qt.AlignmentFlag.AlignHCenter)
        cur.setBlockFormat(fmt_textblock)
        cur.insertText('商品名称中包含 %s' % self.lePNm.text(), fmt_textchar)
        # 表格格式
        fmt_table = QTextTableFormat()
        fmt_table.setBorder(1)
        fmt_table.setBorderStyle(QTextFrameFormat.BorderStyle.BorderStyle_Solid)
        fmt_table.setCellSpacing(0)
        fmt_table.setTopMargin(0)
        fmt_table.setCellPadding(4)
        fmt_table.setAlignment(Qt.AlignmentFlag.AlignHCenter)
        cur.insertTable(self.im.rowCount() + 1, self.im.columnCount(), fmt_table)
        # 数据
        for i in range(self.im.columnCount()):
            header = self.im.headerData(i, Qt.Orientation.Horizontal)
            cur.insertText(header)
            cur.movePosition(QTextCursor.MoveOperation.NextCell)
        for r in range(self.im.rowCount()):
            for c in range(self.im.columnCount()):
                index = self.im.index(r, c)
                cur.insertText(str(index.data()))
                cur.movePosition(QTextCursor.MoveOperation.NextCell)

        doc.print(printer)
